package com.jn.zhinongbao.adapter;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.supportingagriculturaltreasures.adapter.CartAdapter;
import com.example.supportingagriculturaltreasures.bean.Cart;
import com.example.supportingagriculturaltreasures.bean.Order;
import com.example.supportingagriculturaltreasures.database.DatabaseHelper;
import com.example.supportingagriculturaltreasures.utils.PreferenceManager;

import java.util.ArrayList;
import java.util.List;

public class CartActivity extends AppCompatActivity implements CartAdapter.OnCartItemClickListener {

    private RecyclerView recyclerView;
    private TextView tvEmpty;
    private CartAdapter cartAdapter;
    
    // 结算相关控件
    private LinearLayout llCheckoutBar;
    private CheckBox cbSelectAll;
    private TextView tvSelectedCount;
    private TextView tvTotalAmount;
    private Button btnCheckout;
    
    private DatabaseHelper databaseHelper;
    private PreferenceManager preferenceManager;
    private List<Cart> cartList;
    private int currentUserId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart);

        initViews();
        initData();
        loadCartData();
    }

    private void initViews() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("购物车");
        }

        recyclerView = findViewById(R.id.recycler_view);
        tvEmpty = findViewById(R.id.tv_empty);
        
        // 结算相关控件
        llCheckoutBar = findViewById(R.id.ll_checkout_bar);
        cbSelectAll = findViewById(R.id.cb_select_all);
        tvSelectedCount = findViewById(R.id.tv_selected_count);
        tvTotalAmount = findViewById(R.id.tv_total_amount);
        btnCheckout = findViewById(R.id.btn_checkout);

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        
        setupCheckoutListeners();
    }

    private void initData() {
        databaseHelper = new DatabaseHelper(this);
        preferenceManager = new PreferenceManager(this);
        currentUserId = preferenceManager.getCurrentUserId();
    }

    private void loadCartData() {
        if (currentUserId != -1) {
            cartList = databaseHelper.getCartByUserId(currentUserId);
            
            if (cartList.isEmpty()) {
                recyclerView.setVisibility(View.GONE);
                tvEmpty.setVisibility(View.VISIBLE);
                llCheckoutBar.setVisibility(View.GONE);
            } else {
                recyclerView.setVisibility(View.VISIBLE);
                tvEmpty.setVisibility(View.GONE);
                llCheckoutBar.setVisibility(View.VISIBLE);
                
                // 默认所有商品为选中状态
                for (Cart cart : cartList) {
                    cart.setSelected(true);
                }
                
                cartAdapter = new CartAdapter(this, cartList, this);
                recyclerView.setAdapter(cartAdapter);
                
                updateCheckoutInfo();
            }
        } else {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    @Override
    public void onQuantityChanged(Cart cart, int newQuantity) {
        if (newQuantity <= 0) {
            // 删除商品
            boolean result = databaseHelper.removeFromCart(cart.getId());
            if (result) {
                cartList.remove(cart);
                cartAdapter.notifyDataSetChanged();
                Toast.makeText(this, "商品已从购物车移除", Toast.LENGTH_SHORT).show();
                
                if (cartList.isEmpty()) {
                    recyclerView.setVisibility(View.GONE);
                    tvEmpty.setVisibility(View.VISIBLE);
                    llCheckoutBar.setVisibility(View.GONE);
                }
            } else {
                Toast.makeText(this, "删除失败", Toast.LENGTH_SHORT).show();
            }
        } else {
            // 更新数量
            boolean result = databaseHelper.updateCartQuantity(cart.getId(), newQuantity);
            if (result) {
                cart.setQuantity(newQuantity);
                cartAdapter.notifyDataSetChanged();
            } else {
                Toast.makeText(this, "更新失败", Toast.LENGTH_SHORT).show();
            }
        }
        updateCheckoutInfo();
    }

    @Override
    public void onItemClick(Cart cart) {
        // 可以跳转到商品详情页
        Toast.makeText(this, "点击了商品: " + cart.getProductName(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onSelectionChanged(Cart cart, boolean isSelected) {
        updateCheckoutInfo();
    }

    private void setupCheckoutListeners() {
        // 全选/取消全选
        cbSelectAll.setOnCheckedChangeListener((buttonView, isChecked) -> {
            for (Cart cart : cartList) {
                cart.setSelected(isChecked);
            }
            cartAdapter.notifyDataSetChanged();
            updateCheckoutInfo();
        });

        // 结算按钮点击事件
        btnCheckout.setOnClickListener(v -> showPasswordDialog());
    }

    private void updateCheckoutInfo() {
        int selectedCount = 0;
        double totalAmount = 0.0;

        for (Cart cart : cartList) {
            if (cart.isSelected()) {
                selectedCount++;
                totalAmount += cart.getTotalPrice();
            }
        }

        tvSelectedCount.setText("已选" + selectedCount + "件商品");
        tvTotalAmount.setText("合计：¥" + String.format("%.2f", totalAmount));

        // 更新全选状态
        cbSelectAll.setOnCheckedChangeListener(null);
        cbSelectAll.setChecked(selectedCount == cartList.size() && selectedCount > 0);
        cbSelectAll.setOnCheckedChangeListener((buttonView, isChecked) -> {
            for (Cart cart : cartList) {
                cart.setSelected(isChecked);
            }
            cartAdapter.notifyDataSetChanged();
            updateCheckoutInfo();
        });

        // 更新结算按钮状态
        btnCheckout.setEnabled(selectedCount > 0);
    }

    private void showPasswordDialog() {
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_password_input, null);
        EditText etPassword = dialogView.findViewById(R.id.et_password);
        TextView tvPasswordHint = dialogView.findViewById(R.id.tv_password_hint);

        // 设置密码输入框为6位数字限制
        etPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 6) {
                    etPassword.setText(s.subSequence(0, 6));
                    etPassword.setSelection(6);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {}
        });

        android.app.AlertDialog dialog = new android.app.AlertDialog.Builder(this)
                .setTitle("支付密码")
                .setView(dialogView)
                .setPositiveButton("确认支付", null)
                .setNegativeButton("取消", null)
                .create();

        dialog.setOnShowListener(dialogInterface -> {
            Button positiveButton = dialog.getButton(android.app.AlertDialog.BUTTON_POSITIVE);
            positiveButton.setOnClickListener(v -> {
                String password = etPassword.getText().toString().trim();
                if (password.length() != 6) {
                    tvPasswordHint.setText("请输入6位数字密码");
                    tvPasswordHint.setVisibility(View.VISIBLE);
                    return;
                }

                // 模拟密码验证（这里简化处理，实际项目中应该验证真实密码）
                if ("123456".equals(password)) {
                    dialog.dismiss();
                    processCheckout();
                } else {
                    tvPasswordHint.setText("密码错误，请重新输入");
                    tvPasswordHint.setVisibility(View.VISIBLE);
                    etPassword.setText("");
                }
            });
        });

        dialog.show();
    }

    private void processCheckout() {
        List<Cart> selectedCarts = new ArrayList<>();
        for (Cart cart : cartList) {
            if (cart.isSelected()) {
                selectedCarts.add(cart);
            }
        }

        if (selectedCarts.isEmpty()) {
            Toast.makeText(this, "请选择要结算的商品", Toast.LENGTH_SHORT).show();
            return;
        }

        // 创建订单
        boolean allSuccess = true;
        for (Cart cart : selectedCarts) {
            Order order = new Order(
                    currentUserId,
                    cart.getMerchantId(),
                    cart.getProductId(),
                    cart.getProductName(),
                    cart.getProductPrice(),
                    cart.getProductImageUrl(),
                    cart.getQuantity(),
                    "默认收货地址", // 这里应该让用户选择收货地址
                    "默认联系电话"  // 这里应该让用户填写联系电话
            );
            
            order.setStatus(1); // 设置为已付款状态

            boolean success = databaseHelper.addOrder(order);
            if (!success) {
                allSuccess = false;
                break;
            }
        }

        if (allSuccess) {
            // 从购物车中移除已结算的商品
            for (Cart cart : selectedCarts) {
                databaseHelper.removeFromCart(cart.getId());
                cartList.remove(cart);
            }

            cartAdapter.notifyDataSetChanged();
            updateCheckoutInfo();

            if (cartList.isEmpty()) {
                recyclerView.setVisibility(View.GONE);
                tvEmpty.setVisibility(View.VISIBLE);
                llCheckoutBar.setVisibility(View.GONE);
            }

            Toast.makeText(this, "支付成功！已生成" + selectedCarts.size() + "个订单", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(this, "支付失败，请重试", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }
} 